package com.dxb.idmr.utils;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
        e.printStackTrace();
        //判断请求是否为Ajax请求
        if (ControllerUtils.isAjax(request)) { //如果是的话，就直接返回错误信息
            return e.getMessage();
        } else { //如果不是的话，就跳转到错误页面
            ModelAndView mv = new ModelAndView();
            mv.addObject("message", e.getMessage());
            mv.setViewName("error");//这里需要在templates文件夹下新建一个error.html文件用作错误页面
            return mv;
        }
    }
}
